package zj.xinxin.business.handler;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import zj.xinxin.api.moudle.system.api.LoginLogService;
import zj.xinxin.common.constant.SystemConst;
import zj.xinxin.common.result.ResponseResult;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户登录失败 处理器
 * @author junzhou
 * @date 2022/3/23 14:40
 * @since 1.8
 */
@Component
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {

    @Autowired
    private LoginLogService loginLogService;

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        loginLogService.saveLoginLog(httpServletRequest, false);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        httpServletResponse.getWriter()
                .write(JSON.toJSONString(
                        ResponseResult.fail(SystemConst.LOGIN_FAIL, null)));
    }
}

